package com.xiaomi.task;

import com.xiaomi.entity.AlertRecord;
import com.xiaomi.entity.Signal;
import com.xiaomi.service.AlertService;
import com.xiaomi.service.SignalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Configuration
@EnableScheduling
public class BatteryWarnScheduler {

    @Autowired
    private SignalService signalService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private AlertService alertService;

    // 每5分钟执行一次
    @Scheduled(cron = "0/5 * * * * ?")
    @Transactional
    public void scanBatterySignals() {
        List<Signal> signals = signalService.getUnprocessedSignals();
        signals.forEach(signal -> {
            // 让生产者来发送MQ消息，（不需要判断，发送全部的signals）
            rocketMQTemplate.convertAndSend("BATTERY_WARN_TOPIC", signal);
            log.info("发送成功");
            // 更新信号状态
            signalService.updateSignalStatus(signal.getSignalId());
        });
    }
}